package com.wedo.book.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wedo.book.bo.ChapterRequest;
import com.wedo.book.mapper.BookMapper;
import com.wedo.book.mapper.ChapterMapper;
import com.wedo.book.pojo.Book;
import com.wedo.book.pojo.Chapter;
import com.wedo.common.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@CacheConfig(cacheNames = "chapter")
public class ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private BookMapper bookMapper;

    /**
     * 分页查询章节基本信息
     * @param bid
     * @param page
     * @param rows
     * @return
     */
    @Cacheable(key = "'queryChapterByPage'+#bid+'.'+#page+'.'+#rows")
    public PageResult<Chapter> queryChapterByPage(Long bid, Integer page, Integer rows) {
        // 添加查询条件
        Example example = new Example(Chapter.class);
        Example.Criteria criteria = example.createCriteria();
        example.selectProperties("id","bId","sequenceNum","title");

        if (bid == null) {
            return null;
        }
        // bId = bid
        criteria.andEqualTo("bId",bid);

        // 按照章节序号升序
        example.setOrderByClause("`sequence_num` ASC");

        // 添加分页
        PageHelper.startPage(page,rows);

        // 根据bid查询章节信息
        List<Chapter> chapters = this.chapterMapper.selectByExample(example);

        PageInfo<Chapter> pageInfo = new PageInfo<>(chapters);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), chapters);

    }

    @Cacheable(key = "'queryChapterById'+#cid")
    public Chapter queryChapterById(Long cid) {
        return this.chapterMapper.selectByPrimaryKey(cid);
    }

    @Transactional
    @CacheEvict(value = "chapter", allEntries=true)
    public void saveChapter(ChapterRequest chapterRequest) {
        // 获取chapter
        Chapter chapter = new Chapter();
        chapter.setId(null);
        chapter.setbId(chapterRequest.getbId());
        chapter.setTitle(chapterRequest.getTitle());
        chapter.setContext(chapterRequest.getContext());
        if (chapterRequest.getFrontSequenceNum() == null) {
            // 在末尾插入一条
            Integer i = this.chapterMapper.queryMaxSequenceNumByBid(chapter.getbId());
            if (i == null) {
                i = 0;
            }
            chapter.setSequenceNum(i + 1);
        } else {
            // 将章节序号SequenceNum大于插入章节序号的+1
            this.chapterMapper.updateSequenceNumLaterAdd(chapterRequest.getFrontSequenceNum(),chapter.getbId());
            chapter.setSequenceNum(chapterRequest.getFrontSequenceNum() + 1);
        }

        // 保存章节
        this.chapterMapper.insertSelective(chapter);

        // 查询一共多少章节
        Book book = this.bookMapper.selectByPrimaryKey(chapter.getbId());
        // 将book中的总章节数更新
        book.setChapterNumber(book.getChapterNumber() + 1);
        this.bookMapper.updateByPrimaryKeySelective(book);
    }

    @CacheEvict(value = "chapter", allEntries=true)
    public void updateChapter(Chapter chapter) {
        this.chapterMapper.updateByPrimaryKeySelective(chapter);
    }

    @Transactional
    @CacheEvict(value = {"chapter","book"}, allEntries=true)
    public void deleteChapter(Long id) {
        // 查询章节信息
        Chapter chapter = this.chapterMapper.selectByPrimaryKey(id);
        // 删除章节
        this.chapterMapper.deleteByPrimaryKey(chapter.getId());

        // 章节序号之后的章节序号-1
        this.chapterMapper.updateSequenceNumLaterSub(chapter.getSequenceNum(),chapter.getbId());

        // 修改book中总章节数
        // 查询一共多少章节
        Book book = this.bookMapper.selectByPrimaryKey(chapter.getbId());
        // 将book中的总章节数更新
        book.setChapterNumber(book.getChapterNumber() - 1);
        this.bookMapper.updateByPrimaryKeySelective(book);
    }

    @CacheEvict(value = "chapter", allEntries=true)
    public Chapter getLastOrNext(Long cid,Integer type) {
        // 根据章节id获取章节序号
        Chapter chapter = new Chapter();
        chapter.setId(cid);
        Chapter chapterOld = this.queryChapterById(cid);

        // 设置自定义查询条件
        // 添加查询条件
        Example example = new Example(Chapter.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("bId",chapterOld.getbId());
        if (type == -1) {
            criteria.andEqualTo("sequenceNum",chapterOld.getSequenceNum() - 1);
        } else if(type == 1) {
            criteria.andEqualTo("sequenceNum",chapterOld.getSequenceNum() + 1);
        }
        Chapter chapters = this.chapterMapper.selectOneByExample(example);
        return chapters;
    }
}
